import {Token} from '@/store/modules/user/type'
import {closeSocket} from '@/service/socket/socket'
import {userApi} from '@/service/api'
import {UserProfileExtVo} from '@/service/api/modules/user/response'
import { MyStoreInfo } from '@/service/api/modules/store/response'

export const useUserStore = defineStore({
  id: 'userStore',
  state: () => ({
    token: {
      accessToken: '',
      expireTime: 0
    } as Token, //当前的AccessToken
    userInfo: null as UserProfileExtVo | null, //当前登录用户的信息
    subscribeMessageStatus: false as boolean, //是否已授权订阅消息通知
    storeInfo: null as MyStoreInfo | null //我的店铺信息
  }),
  getters: {
    accessToken: (state): string => {
      const {accessToken, expireTime} = state.token
      if (!!accessToken && expireTime > Date.now()) {
        return accessToken
      } else {
        return ''
      }
    }
  },
  actions: {
    // 刷新AccessToken
    refreshToken(): void {
      const refreshToken = uni.getStorageSync('REFRESH_TOKEN')
      if (!!refreshToken) {
        const refreshTokenExpireIn = uni.getStorageSync('REFRESH_TOKEN_EXPIRE_IN')
        //refreshToken失效
        if (!!refreshTokenExpireIn && refreshTokenExpireIn < new Date().getTime()) {
          return
        }
        userApi.refreshToken({refreshToken}).then(ignore => {
        }).catch(ignore => {
          //清除用户数据
          this.setUserInfo(null)
          uni.removeStorageSync('userInfo')
        })
      }
    },
    /**
     * 存储AccessToken信息
     * @param accessToken token
     * @param expireTime 过期时间
     */
    setAccessToken(accessToken: string, expireTime: number): void {
      this.token = {
        accessToken: accessToken,
        expireTime: expireTime
      }
    },
    // 存储UserInfo
    setUserInfo(userInfo: any): Promise<void> {
      return new Promise<void>(async (resolve, reject) => {
        if (!!userInfo) {
          await uni.setStorage({
            key: 'userInfo',
            data: userInfo,
            success: async () => {
              this.userInfo = userInfo
              resolve()
            },
            fail: () => reject()
          })
        } else {
          this.logOut()
        }
      })
    },
    // 存储StoreInfo
    setStoreInfo(storeInfo: any): Promise<void> {
      return new Promise<void>(async (resolve, reject) => {
        if (!!storeInfo) {
          await uni.setStorage({
            key: 'storeInfo',
            data: storeInfo,
            success: async () => {
              this.storeInfo = storeInfo
              resolve()
            },
            fail: () => reject()
          })
        } else {
          this.logOut()
        }
      })
    },
    // 退出登录
    logOut(): void {
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('storeInfo')
      uni.removeStorageSync('REFRESH_TOKEN')
      uni.removeStorageSync('REFRESH_TOKEN_EXPIRE_IN')
      closeSocket().then(() => {
      })
      this.$reset()
    }
  }
})
